package org.bambrikii.examples.rutext.lexer.custom;

import java.text.DecimalFormat;

import org.bambrikii.examples.rutext.SentenceBuilder;
import org.bambrikii.examples.rutext.lexer.ILexer;
import org.bambrikii.examples.rutext.lexer.impl.LexerBase;
import org.bambrikii.examples.rutext.parser.IParser;
import org.bambrikii.examples.rutext.parser.ParserException;

public class SentenceLexer extends LexerBase<String> {

	private static final String PATTERN = "###.#######";
	private static DecimalFormat NUMBER_FORMATTER;

	public SentenceLexer(IParser parser) {
		super(parser);
		NUMBER_FORMATTER = new DecimalFormat(PATTERN);
		addChild(new NewLineLexer(parser));
		addChild(new NumberLexer(parser));
		addChild(new WordLexer(parser));
	}

	public void setNumberFormatter(DecimalFormat format) {
		NUMBER_FORMATTER = format;
	}

	@Override
	public String lex() throws ParserException {
		SentenceBuilder sb = new SentenceBuilder();
		while (/* getParser().hasNewLine() || */hasNext()) {
			for (ILexer<?> child : getChildren()) {
				Object obj = child.lex();
				if (obj != null) {

					if (child instanceof NewLineLexer) {
						sb.addNewLine();
					} else if (child instanceof NumberLexer) {
						Double currentValue = (Double) obj;
						sb.addWord(NUMBER_FORMATTER.format(currentValue));
					} else if (child instanceof WordLexer) {
						String currentValue = (String) obj;
						sb.addWord(currentValue.toString());
					}
				}
			}
		}
		return sb.build();
	}
}
